package com.example.toy.core.version;

import java.util.concurrent.atomic.AtomicLong;
import lombok.EqualsAndHashCode;
import lombok.Getter;

@Getter
@EqualsAndHashCode(of = "timestamp")
public class ToyVersion implements Comparable<ToyVersion> {

  public static final ToyVersion FIRST_VERSION = new ToyVersion(0);
  public static final ToyVersion LATEST_VERSION = new ToyVersion(Long.MAX_VALUE);

  private final long timestamp;

  public ToyVersion(long timestamp) {
    this.timestamp = timestamp;
  }

  private static final AtomicLong id = new AtomicLong(System.currentTimeMillis());

  public static final ToyVersion nextVersion() {
    return new ToyVersion(id.incrementAndGet());
  }

  @Override
  public int compareTo(ToyVersion o) {
    if (o == null) {
      return -1;
    }
    return Long.compare(this.timestamp, o.timestamp);
  }

  @Override
  public String toString() {
    return "ToyVersion: " + timestamp;
  }

  /**
   * 当前版本戳 + 1
   *
   * @return
   */
  public ToyVersion bigger() {
    return new ToyVersion(timestamp + 1);
  }

  /**
   * 当前版本戳 - 1
   *
   * @return
   */
  public ToyVersion smaller() {
    return new ToyVersion(timestamp - 1);
  }

  /**
   * 判断是否比指定版本大
   *
   * @param version
   * @return
   */
  public boolean bigThan(ToyVersion version) {
    return this.timestamp > version.timestamp;
  }

  /**
   * 判断是否比指定版本大或等于
   *
   * @param version
   * @return
   */
  public boolean bigThanOrEquals(ToyVersion version) {
    return this.timestamp >= version.timestamp;
  }
  /**
   * 判断是否比指定版本小
   *
   * @param version
   * @return
   */
  public boolean smallThan(ToyVersion version) {
    return this.timestamp < version.timestamp;
  }
  /**
   * 判断是否比指定版本小或等于
   *
   * @param version
   * @return
   */
  public boolean smallThanOrEquals(ToyVersion version) {
    return this.timestamp <= version.timestamp;
  }
}
